package com.fingard.dsp.bank.directbank.mbs01;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.dsp.bank.directbank.spdb01.authforrec.StringUtils;
import com.fingard.net.WebRequest;
import com.fingard.text.StringHelper;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.UnsupportedEncodingException;
import java.util.*;

public class MBS01Base extends DirectBase {
    protected String getCharset() {
        return getBankConfig().getCharset("utf-8");
    }
    //MD5加密获取sign
    public String getSignData(Map map, String secretKey)throws Exception{
        map.put("secretKey",secretKey);
        String data = coverMap2String(map);
        WriteBankLogLn("待签名串："+data);
        return org.springframework.util.DigestUtils.md5DigestAsHex(data.getBytes("UTF-8"));
    }

    //去除map中的key为sign
    public String coverMap2String(Map data) {
        TreeMap tree = new TreeMap();
        Iterator it = data.entrySet().iterator();

        while(it.hasNext()) {
            Map.Entry en = (Map.Entry)it.next();
            String value = "";
            if (
                    !"sign".equals(((String)en.getKey()).trim()) &&
                            !"qCode".equals(((String)en.getKey()).trim()) &&
                            !"qDes".equals(((String)en.getKey()).trim()) &&
                            !"showURL".equals(((String)en.getKey()).trim()) &&
                            !"".equals(en.getValue())
                    )
            {
                tree.put(en.getKey(), en.getValue());
            }
        }

        it = tree.entrySet().iterator();
        StringBuffer sf = new StringBuffer();

        while(it.hasNext()) {
            Map.Entry en = (Map.Entry)it.next();
            sf.append((String)en.getKey() + "=" + String.valueOf(en.getValue()) + "&");
        }

        return sf.substring(0, sf.length() - 1);
    }

    /**
     * 发送并获取返回
     */
    protected String[] sendToBank(String p_reqStr,String url) throws Exception {
        String[] retStr = new String[]{"", ""};
        WriteBankLogLn("2.提交银行的地址：" + url);
        String charsetName = "utf-8";
        WriteBankLogStep2(p_reqStr);
        WebRequest tmpWebRequest = new WebRequest(url);
        tmpWebRequest.setConnectTimeout(60000);
        tmpWebRequest.setRequestProperty("Content-Type", "application/json");
        tmpWebRequest.setRequestProperty("connection", "Close");
        byte[] tmpToWriteBytes = p_reqStr.getBytes(charsetName);
        retStr = tmpWebRequest.upload(tmpToWriteBytes, charsetName);
        WriteBankLogStep3(retStr[1]);
        return retStr;
    }
}
